<?php

namespace App\Http\Controllers\Admin\Setting\Wechat;

use App\Http\Controllers\Admin\Controller;
use App\Models\WechatMessage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Response;

class WeChatMessageController extends Controller
{
    protected array $validateMessages = [
        'key.*' => '请输入输入消息回复关键词',
        'msg_type.*' => '请输入输入消息回复类型',
        'content.*' => '请输入输入消息回复内容',
        'extra_json.*' => '请输入输入消息回复内容',
        'status.*' => '请输入正确的状态',
        'sort.*' => '请输入排序',
    ];


    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    public function index(): Response
    {
        $list = WechatMessage::query()->orderBy('sort')->paginate(10)->through(fn ($message) => [
            'id' => $message->id,
            'key' => $message->key,
            'msg_type' => $message->msg_type,
            'content' => $message->content,
            'extra_json' => $message->extra_json,
            'status' => $message->status,
            'sort' => $message->sort,
            'created_at' => $message->created_at->format('Y-m-d H:i:s'),
        ]);
        return $this->inertia('setting/wechat/message/index',[
            'data' => $list->items(),
            'pagination' => [
                'total' => $list->total(),
                'page' => $list->currentPage(),
                'pageSize' => $list->perPage(),
            ],
        ]);
    }

    public function show($id): array
    {
        $message = WechatMessage::query()->find($id);
        return [
            'data' => $message,
        ];
    }

    public function store(): JsonResponse
    {
        $params = $this->validate(
            $this->request,
            [
                'key' => 'required|string',
                'msg_type' => 'required|string',
                'content' => 'nullable|string',
                'extra_json' => 'nullable|array',
                'status' => 'required|integer',
                'sort' => 'required|integer',
            ],
            $this->validateMessages
        );
        WechatMessage::query()->create($params);
        return $this->responseCreated();
    }
    public function update($id): JsonResponse
    {
        $params = $this->validate(
            $this->request,
            [
                'key' => 'required|string',
                'msg_type' => 'required|string',
                'content' => 'nullable|string',
                'extra_json' => 'nullable|array',
                'status' => 'required|integer',
                'sort' => 'required|integer',
            ],
            $this->validateMessages
        );
        $message = WechatMessage::query()->find($id);
        $message->update($params);
        return $this->responseSuccess();
    }

    public function destroy($id): JsonResponse
    {
        $message = WechatMessage::query()->find($id);
        $message->delete();
        return $this->responseDeleted();
    }


}
